package leetcode.editor.week.week306;

import java.util.LinkedList;

public class Solution6149 {
    // https://leetcode.cn/problems/node-with-highest-edge-score/
    public int edgeScore(int[] edges) {
        int n = edges.length;
        LinkedList<Integer>[] graph = new LinkedList[n];

        for (int i = 0; i < n; i++) {
            int from = i;
            int to = edges[i];
            if (graph[to] == null) graph[to] = new LinkedList<>();
            graph[to].add(from);
        }

        // 注意溢出
        long max = 0;
        int idx = 0;
        for (int i = 0; i < n; i++) {
            if (graph[i] == null) continue;
            LinkedList<Integer> list = graph[i];
            long sum = 0;
            for (Integer val : list) {
                sum += val;
            }

            if (sum > max) {
                max = sum;
                idx = i;
            }
        }

        return idx;
    }
}
